package geo.google.mapping;

import com.magenta.maxoptra.gis.GeoException;
import com.magenta.mrs.geocoding.mapping.XmlMappingFunctor;

import javax.xml.transform.*;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.ByteArrayOutputStream;

/**
 * Use and XSLT to convert an KML xml doc to other format.
 *
 * @author jliang
 * @since 1.2
 */
public class XSLTMappingFunctor implements XmlMappingFunctor<String> {

    private Source _xsltSource;

    public XSLTMappingFunctor(Source xsltSource) {
        super();
        _xsltSource = xsltSource;
    }

    public Source getXsltSource() {
        return _xsltSource;
    }

    public void setXsltSource(Source xsltSource) {
        _xsltSource = xsltSource;
    }

    public String execute(String xml) throws GeoException {

        Source source = new StreamSource(xml);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Result res = new StreamResult(out);
        TransformerFactory transFact = TransformerFactory.newInstance();
        Transformer trans;

        try {
            trans = transFact.newTransformer(_xsltSource);
            trans.transform(source, res);
        }
        catch (TransformerConfigurationException e) {
            throw new GeoException(e);
        }
        catch (TransformerException e) {
            throw new GeoException(e);
        }

        return out.toString();
    }

}